package com.run.guifeng.controller.userController;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.run.guifeng.commom.Constants;
import com.run.guifeng.config.AlipayConfig;
import com.run.guifeng.model.dto.OrderDTO;
import com.run.guifeng.model.dto.PayDto;
import com.run.guifeng.model.dto.ShoppingCartDTO;
import com.run.guifeng.model.dto.UserDto;
import com.run.guifeng.model.entity.*;
import com.run.guifeng.service.*;
import com.run.guifeng.util.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private Alipay_wap alipay_wap;

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressService addressService;


    @PostMapping("/register/{checkCode}")
    public Result register(@PathVariable String checkCode, @RequestBody User user, HttpSession httpSession){
        if (httpSession.getAttribute("code").equals(checkCode)) {
            System.out.println(user);
            userService.register(user);
            return Result.success("success");
        }
        return Result.registerError("checkcode error");
    }

    @PostMapping
    public Result login(@RequestBody UserDto userDto){

        User user = userService.login(userDto.getPhone(), userDto.getPassword());
        if(user == null){
            return Result.loginError();
        }else{
            Result success = Result.success("success");
            user.setPassword(null);
            success.setData(user);
            return success;
        }
    }
    @PostMapping("/updateInfo")
    public Result updatePassword(@RequestBody User user){
        //做更新
        userService.updateInfo(user);
        return Result.success("success");
    }

    @GetMapping("/orders/{userid}/{page}/{size}")
    public Result getMyOrders(@PathVariable("userid") Integer userid,
                              @PathVariable("page") Integer page,
                              @PathVariable("size") Integer size){

        Page<Order> myOrders = orderService.getMyOrders(page, size, userid);
        Result result = Result.success("success");
        result.setData(myOrders);
        return result;
    }

    @GetMapping("/orders/{userid}")
    public Result getMyOrdersList(@PathVariable String userid){
        List<Order> list = orderService.getMyOrdersList(userid);
        Result result = Result.success("success");
        result.setData(list);
        return result;
    }


    @PostMapping("/pay")
    public String alipay(@RequestBody PayDto payDto) throws AlipayApiException {
        Order order = orderService.getOrderByOrderNo(payDto.getOrderNo());
        List<OrderItem> orderItems = orderService.getOrderItems(order.getId());
        String form = alipay_wap.alipay(order,payDto.getGoodsName().toString());
        order.setOrderStatus(1);
        orderService.paySuccess(payDto.getOrderNo(),1);
        return form;
        }

    @PutMapping("/update/cart")
    public Result updateCartItemCount(@RequestBody ShoppingCartItem shoppingCartItem){
        shoppingCartService.updateCartItem(shoppingCartItem);
        return Result.success("success");
    }

    @PostMapping("add/item")
    public Result addCartItem(@RequestBody ShoppingCartItem shoppingCartItem){
        boolean flag = shoppingCartService.saveCartItem(shoppingCartItem);
        if(flag)
            return Result.success("success");
        return Result.addError("add error");
    }

    @GetMapping("/orders/{id}/{page}")
    public Result getOrders(@PathVariable("page") Integer page,
                            @PathVariable("id") Integer userid){
        Page<Order> myOrders = orderService.getMyOrders(page, Constants.ORDER_SEARCH_PAGE_LIMIT, userid);
        Result result = Result.success("success");
        result.setData(myOrders);
        return result;
    }

    @GetMapping("/orders/status/{userid}/{page}/{status}")
    public Result getOrdersByStatus(@PathVariable("userid")Integer userid,
                                    @PathVariable("page") Integer page,
                                    @PathVariable ("status")Integer status){
        Page<Order> myOrders = orderService.getMyOrdersByStatus(userid, page, status);
        Result result = Result.success("success");
        result.setData(myOrders);
        return result;
    }

    @PostMapping("/create")
    public Result createOrder(@RequestBody OrderDTO orderDTO){
        Integer userid = orderDTO.getUserid();
        String address = addressService.getAddressByUserid(userid);
        orderDTO.setUserAddress(address);
        Order order = OrderDTOUtil.initOrder(orderDTO);
        List<OrderItem> orderItemList = OrderItemUtil.initOrderItem(orderDTO,order.getOrderNo());
        orderService.saveOrder(order);
        orderService.saveOrderItem(orderItemList);
        Result result = Result.success("success");
        result.setData(address);
        return result;
    }

    @GetMapping("/cart/{userid}")
    public Result getMyShoppingCartItems(@PathVariable Long userid){
        List<ShoppingCartDTO> myShoppingCartItems = shoppingCartService.getMyShoppingCartItems(userid);
        Result result = Result.success("success");
        result.setData(myShoppingCartItems);
        System.out.println(result);
        return result;
    }
    @GetMapping("/goods/list")
    public Result list() {
        Result result = ResultGenerator.genSuccessResult(goodsService.getMallGoodsPage(
                1,
                100,
                null, null, null, null));
        return result;

    }

}
